package com.ts.enterprise.common.service.impl;


import com.ts.enterprise.common.consts.SmsConstants;
import com.ts.enterprise.common.utils.RedisUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.ts.enterprise.common.consts.CommonConstant;
import com.ts.enterprise.common.config.AliAccountConfig;
import com.ts.enterprise.common.service.CommonService;
import com.ts.enterprise.common.service.SmsManagerService;
import com.ts.enterprise.enums.ApiCode;
import com.ts.enterprise.enums.RedisKeyEnum;
import com.ts.enterprise.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @ProjectName: dg-platform
 * @Package: com.central.service
 * @ClassName: CommonServiceImpl
 * @Author: Administrator
 * @Description:
 * @Date: 2021/7/15 13:36
 * @Version: 1.0
 */
@Service
@Slf4j
public class CommonServiceImpl implements CommonService {

    @Autowired
    private AliAccountConfig aliAccountConfig;

    @Autowired
    private SmsManagerService smsManagerService;

    private static final Long ZERO = 0L;

    @Value("${system.isDebug}")
    private Boolean isDebug;

    @Override
    public Boolean sendSmsCode(String mobile) {
        //短信服务
        String smsCode = SmsConstants.generateSmsCode();
        if (true){
            smsCode = CommonConstant.TEST_SMS_CODE;
        }else {
            smsManagerService.sendSmsCode(mobile, smsCode);
        }
        RedisUtil.set(RedisKeyEnum.getRedisKey(RedisKeyEnum.SMS_CODE, mobile), smsCode, RedisKeyEnum.SMS_CODE.getExpiredTime());
        return true;
    }

    @Override
    public Boolean checkSmsCode(String mobile, String smsCode) {
        return smsManagerService.checkSmsCode(mobile, smsCode);
    }

    @Override
    public Long getDefaultZero(Long applyCompanyId) {
        return null == applyCompanyId ? ZERO : applyCompanyId;
    }


    @Override
    public Map<String, String> getAliOssAppTokenWithSign(HttpServletRequest request, HttpServletResponse response) {
        String json = RedisUtil.get(RedisKeyEnum.OSS_APP_STS_TOKEN_WITH_SIGN.getPrefix());
        if (!StringUtils.isEmpty(json)){
            return JSON.parseObject(json, HashMap.class);
        }
        Map<String, String> respMap = new LinkedHashMap<String, String>();
        String accessId = aliAccountConfig.getAccessKeyId(); // 请填写您的AccessKeyId。
        String accessKey = aliAccountConfig.getAccessKeySecret(); // 请填写您的AccessKeySecret。
        String endpoint = aliAccountConfig.getEndpoint(); // 请填写您的 endpoint。
        String bucket = aliAccountConfig.getBucketName(); // 请填写您的 bucketname 。
        String host = "https://" + bucket + "." + endpoint; // host的格式为 bucketname.endpoint
        // callbackUrl为上传回调服务器的URL，请将下面的IP和Port配置为您自己的真实信息。
        String dir = DateUtil.format(new Date(),"yyyy/MM/dd/"); // 用户上传文件时指定的前缀。

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
        try {
            long expireEndTime = System.currentTimeMillis() + 1000L * RedisKeyEnum.OSS_APP_STS_TOKEN_WITH_SIGN.getExpiredTime();
            Date expiration = new Date(expireEndTime);
            // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("bucket", bucket);
            respMap.put("endpoint", endpoint);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
        } catch (Exception e) {
            throw new BusinessException(ApiCode.OSS_TOKEN_FAIL);
        } finally {
            ossClient.shutdown();
        }
        RedisUtil.set(RedisKeyEnum.OSS_APP_STS_TOKEN_WITH_SIGN.getPrefix(), JSONObject.toJSONString(respMap),RedisKeyEnum.OSS_APP_STS_TOKEN_WITH_SIGN.getExpiredTime());
        return respMap;
    }

    /**
     *
     */
    private static final long serialVersionUID = 5522372203700422672L;
    // 目前只有"cn-hangzhou"这个region可用, 不要使用填写其他region的值
    public static final String REGION_CN_HANGZHOU = "cn-hangzhou";
    public static final String STS_API_VERSION = "2015-04-01";
    protected AssumeRoleResponse assumeRole(String accessKeyId, String accessKeySecret, String roleArn,
                                            String roleSessionName, String policy, ProtocolType protocolType, long durationSeconds) throws ClientException
    {
        try {
            // 创建一个 Aliyun Acs Client, 用于发起 OpenAPI 请求
            IClientProfile profile = DefaultProfile.getProfile(REGION_CN_HANGZHOU, accessKeyId, accessKeySecret);
            DefaultAcsClient client = new DefaultAcsClient(profile);

            // 创建一个 AssumeRoleRequest 并设置请求参数
            final AssumeRoleRequest request = new AssumeRoleRequest();
            request.setVersion(STS_API_VERSION);
            request.setMethod(MethodType.POST);
            request.setProtocol(protocolType);

            request.setRoleArn(roleArn);
            request.setRoleSessionName(roleSessionName);
//			request.setPolicy(policy);
            request.setDurationSeconds(durationSeconds);

            // 发起请求，并得到response
            final AssumeRoleResponse response = client.getAcsResponse(request);

            return response;
        } catch (ClientException e) {
            throw e;
        }
    }



}
